import pygame
from pygame.locals import *
from sys import exit

# TODO
# Grid hacer Static?

class Grid:
    
    _board = {}
    
    def __init__(self, position, size, square):
        
        self.rows, self.cols = size
        self.sqr_width, self.sqr_height = square
        self.left, self.top = position
        
    def __getitem__(self, key):
        return self._board[key]

    def load(self):
        for i in range(0,self.rows):
            for j in range(0, self.cols):
                n_top = self.top + i*self.sqr_height
                n_left = self.left + j*self.sqr_width

                self._board[str(i)+'_'+str(j)] = Rect((n_left, n_top), (self.sqr_width,self.sqr_height))

    def get_position(self, point):
        col = (point[0]-self.left) / self.sqr_width
        row = (point[1]-self.top) / self.sqr_height
        
        if row >= self.rows or col >= self.cols or row < 0 or col < 0:
            return None
        
        return (row,col)
        
    def show(self, screen):
        color = (255,255,255)

        for rect in self._board.itervalues():
            pygame.draw.rect(screen, color, rect, 1)
    
    

if __name__ == "__main__":
    grid = Grid((130,56), (13,11), (39,39))
    
    grid.load()
    
   # print grid.board["2_1"]
    row = 4
    col = 3
    key = str(row) + '_' + str(col)
    print grid[key]
    
    print grid.get_position((270,241))
    
    
    
